package edu.rutgers.moko.data.util;

/*
 * Copyright © 2008 JavaEECoding.com. All rights reserved.
 */

import java.util.LinkedHashMap;
import java.util.Map;

/***
 * A LRU (Least Recently Used) Cache.
 */
public class LRUCache<K,V> extends LinkedHashMap<K,V>
{
	private static final long serialVersionUID = 1L;
	// The max size of this cache.
    private static int MAX_ENTRIES = 1000;
    
    public LRUCache(Integer max) 
    {
        // to create a linked hash map whose order of iteration is the order in
        // which its entries were last accessed, from least-recently accessed 
        // to most-recently (access-order). Invoking the put or get method results 
        // in an access to the corresponding entry.
        super(max * 4 / 3 + 1, 0.75f, true);
        MAX_ENTRIES = max;
    }

    // This method is invoked by put and putAll after inserting a new entry into
    // the map. It allows the map to grow up to 8 entries and then 
    // delete the eldest entry each time a new entry is added, maintaining a 
    // steady state of 8 entries.
    protected boolean removeEldestEntry(Map.Entry eldest) 
    { 
        return this.size() > MAX_ENTRIES; 
    }
}

